package com.timguan.render.dataprocessor.processor;

import com.timguan.render.api.entity.cms.CMSDataProcessorParamInfo;
import com.timguan.render.dataapi.api.ICmsDataManager;
import com.timguan.render.dataapi.domain.CmsDataDO;
import com.timguan.render.dataprocessor.filter.TimeVaildFilter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 查询cms_data表获取endTime>当前时间的数据列表
 * Created by guankaiqiang on 2015/3/21.
 */
public class EndTimeVaildProcessor extends DataProcessor {
    private static final Logger logger = LoggerFactory.getLogger(EndTimeVaildProcessor.class);
    @Autowired
    private ICmsDataManager cmsDataManagerImpl;
    @Autowired
    private TimeVaildFilter timeVaildFilter;

    static class WeightComparator implements Comparator<CmsDataDO> {
        @Override
        public int compare(CmsDataDO o1, CmsDataDO o2) {
            int leftWeight = 0, rightWeight = 0;
            if (o1.getWeight() != null) {
                leftWeight = o1.getWeight().intValue();
            }
            if (o2.getWeight() != null) {
                rightWeight = o2.getWeight().intValue();
            }
            if (leftWeight == rightWeight) {
                return 0;
            } else if (leftWeight > rightWeight) {
                return -1;
            } else {
                return 1;
            }
        }
    }

    private static final Comparator WEIGHT_COMPARE = new WeightComparator();

    protected List<Object> execute(CommonParametersWrapper wrapper, Map<String, String> params) {
        if (params != null && params.get(PROCESSOR_PARAM_DATALISTID) != null) {
            int listId = Integer.valueOf(params.get(PROCESSOR_PARAM_DATALISTID));
            List<CmsDataDO> cmsDataDOs = cmsDataManagerImpl.selectByListId(listId);
            Map<String, String> filterParams = new HashMap<String, String>();
            filterParams.put(START_DISPLAY_TIME, String.valueOf(System.currentTimeMillis()));
            if (StringUtils.isNotBlank(params.get(ADVANCE))) {
                try {
                    long advance = Long.parseLong(params.get(ADVANCE)) * 60 * 60 * 1000;
                    filterParams.put(END_DISPLAY_TIME, String.valueOf(System.currentTimeMillis() + advance));
                } catch (Exception e) {
                    logger.error("parse advance failed!", e);
                }
            }
            cmsDataDOs = dataFilterChain.doFilter(cmsDataDOs, filterParams);
            cmsDataDOs = getSortedCmsDataList(cmsDataDOs);
            return appendSpm(wrapper, cmsDataDOs, Constants.SPM_START);
        }
        return null;
    }

    /**
     * 分段排序
     *
     * @param cmsDataDOs
     * @return
     */
    public List<CmsDataDO> getSortedCmsDataList(List<CmsDataDO> cmsDataDOs) {
        if (cmsDataDOs != null) {
            Date now = new Date();
            List<CmsDataDO> cmsDataList = new ArrayList<CmsDataDO>();
            List<CmsDataDO> notStartedDataList = new ArrayList<CmsDataDO>();
            for (CmsDataDO data : cmsDataDOs) {
                if (data.getStarttime() != null && now.before(data.getStarttime())) {
                    notStartedDataList.add(data);
                } else {
                    cmsDataList.add(data);
                }
            }
            Collections.sort(notStartedDataList, WEIGHT_COMPARE);
            Collections.sort(cmsDataList, WEIGHT_COMPARE);
            cmsDataList.addAll(notStartedDataList);
            return cmsDataList;
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //使用时需要创建数据列表
        needCreateDatalistWhenUsed = true;
        description = "排期预告";
        paramInfos = new CMSDataProcessorParamInfo[1];
        CMSDataProcessorParamInfo dataProcessorParamInfo = new CMSDataProcessorParamInfo();
        dataProcessorParamInfo.setName(ADVANCE);
        dataProcessorParamInfo.setDescription("提前预告(小时),默认不预告");
        paramInfos[0] = dataProcessorParamInfo;
        dataFilterChain.add(timeVaildFilter);
    }
}
